package com.atguigu.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.base.ExceptionHnadler.CustomException;
import com.atguigu.edu.entity.Subject;
import com.atguigu.edu.excel.SubjectData;
import com.atguigu.edu.service.SubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private SubjectService subjectService;

    public SubjectExcelListener(){}

    //创建有参数构造，传递subjectService用于操作数据库
    public SubjectExcelListener(SubjectService subjectService){
        this.subjectService=subjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData==null){
            throw new CustomException(20001,"文件数据为空");
        }
        //一行一行读取，每次读取有两个值，第一个值一级分类，第二个值二级分类
        Subject one = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
        if(one==null){
            //没有相同的一级分类就进行添加
            one=new Subject();
            one.setParentId("0");
            one.setTitle(subjectData.getOneSubjectName());//设置一级分类名称
            subjectService.save(one);
        }
        //获取一级分类id值
        String pid=one.getId();
        //添加二级分类
        //判断二级分类是否重复
        Subject two = this.existTowSubject(subjectService, subjectData.getTwoSubjectName(),pid);
        if(two==null){
            two=new Subject();
            two.setParentId(pid);
            two.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(two);
        }
    }
    //判断一级分类不能重复添加
    private Subject existOneSubject(SubjectService subjectService, String name){
        QueryWrapper<Subject> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",0);
        Subject one = subjectService.getOne(queryWrapper);
        return one;
    }
    //判断二级分类不能重复添加
    private Subject existTowSubject(SubjectService subjectService, String name,String pid){
        QueryWrapper<Subject> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",pid);
        Subject tow = subjectService.getOne(queryWrapper);
        return tow;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
